﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AjConsor.Entities;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Automapping;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace AjConsor.FluentNh
{
    class Program
    {
        private const string DbFile = "AjConsor.db";

        static void Main(string[] args)
        {
            Consorcio cons1 = new Consorcio()
            {
                Nombre = "Edificio 1",
                Domicilio = "Calle 1"
            };

            Unidad uni1 = new Unidad()
            {
                Descripcion = "Departamento 1"
            };

            Unidad uni2 = new Unidad()
            {
                Descripcion = "Departamento 2"
            };

            cons1.AddUnidad(uni1);
            cons1.AddUnidad(uni2);

            var factory = CreateSessionFactory();

            using (var session = factory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    session.Save(cons1);
                    session.Save(uni1);
                    session.Save(uni2);

                    transaction.Commit();
                }
            }

            using (var session = factory.OpenSession())
            {
                Consorcio consorcio = session.Get<Consorcio>(1);

                Console.WriteLine(consorcio.Id);
                Console.WriteLine(consorcio.Nombre);

                foreach (var unidad in consorcio.Unidades)
                {
                    Console.WriteLine(unidad.Id);
                    Console.WriteLine(unidad.Descripcion);
                    Console.WriteLine(unidad.Consorcio.Nombre);
                }
            }

            Console.ReadLine();
        }

        private static ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
                .Database(SQLiteConfiguration.Standard
                    .UsingFile(DbFile)
                    )
                .Mappings(m =>
                    m.AutoMappings
                        .Add(AutoMap.AssemblyOf<Consorcio>()
                        ))
                .ExposeConfiguration(BuildSchema)
                .BuildSessionFactory();
        }

        private static void BuildSchema(Configuration configuration)
        {
            (new SchemaExport(configuration)).Create(true, true);
        }
    }
}
